﻿using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using PoemGame.Domain.Services;

namespace PoemDomain.Services.Remote
{
    public class CheckAnswerServiceRemote : ICheckAnswerService
    {
        private readonly IConfiguration _configuration;
        public CheckAnswerServiceRemote(IConfiguration configuration)
        {
            _configuration=configuration;
        }
        public async Task<bool> CheckAnswer(CheckAnswerServiceInput game, string answer)
        {
            var remoteurl = _configuration["CheckAnswerServices:" + game.MainType + "_" + game.SubType];
            if (!string.IsNullOrEmpty(remoteurl))
            {
                var data = new
                {
                    maintype=game.MainType,
                    subtype=game.SubType,
                    gamecondition=game.GameCondition,
                    properanswers=game.ProperAnswers.ToArray(),
                    answer=answer
                };
                HttpContent httpContent = new StringContent(JsonSerializer.Serialize(data));
                httpContent.Headers.ContentType= new MediaTypeHeaderValue("application/json");
                var apiClient = new HttpClient();
                var response = await apiClient.PostAsync(remoteurl,httpContent);
                var res = await response.Content.ReadFromJsonAsync<bool>();
                return res;
            }
            throw new Exception("配置文件中没有定义");
        }
    }
}